package com.laolang.pluto.common.util;

import cn.hutool.core.util.StrUtil;
import com.laolang.pluto.common.consts.IBizCode;
import com.laolang.pluto.common.exception.BusinessException;
import lombok.experimental.UtilityClass;
import org.slf4j.Logger;

/**
 * 通用断言工具类
 *
 * @author laolang
 * @date 2021-07-2021/7/31 15:34
 */
@UtilityClass
public class AssertUtil {
    private static final int ASSERT_ORIGIN_STACK_INDEX = 4;

    public static <T> T notNull(Logger logger, T object, IBizCode bizCode, String logMsg) {
        if (null == object) {
            if (StrUtil.isNotBlank(logMsg)) {
                LogUtil.error(logger, logMsg, ASSERT_ORIGIN_STACK_INDEX);
            } else {
                LogUtil.error(logger, bizCode.getMsg(), ASSERT_ORIGIN_STACK_INDEX);
            }
            throw new BusinessException(bizCode);
        }
        return object;
    }

    public static <T> T isNull(Logger logger, T object, IBizCode bizCode, String logMsg) {
        if (null != object) {
            if (StrUtil.isNotBlank(logMsg)) {
                LogUtil.error(logger, logMsg, ASSERT_ORIGIN_STACK_INDEX);
            } else {
                LogUtil.error(logger, bizCode.getMsg(), ASSERT_ORIGIN_STACK_INDEX);
            }
            throw new BusinessException(bizCode);
        }
        return object;
    }

    public static void isTrue(Logger logger, boolean expression, IBizCode bizCode, String logMsg) {
        if (!expression) {
            if (StrUtil.isNotBlank(logMsg)) {
                LogUtil.error(logger, logMsg, ASSERT_ORIGIN_STACK_INDEX);
            } else {
                LogUtil.error(logger, bizCode.getMsg(), ASSERT_ORIGIN_STACK_INDEX);
            }
            throw new BusinessException(bizCode);
        }
    }
}
